<?php

/******************************************************************

	Name: 索引操作类
	Author: 徐立 ( Eks Tsui )
	Email: ekstsui@gmail.com
	QQ: 1181601

/******************************************************************/

if ( !defined ( 'IN_SYSTEM' ) )
{
	exit ( 'Access Denied' );
}

class clsIndex
{
	var $db;
	var $dbConfig;
	var $idxSettings;
	var $fields;
	var $tableNameSplitor = '_';

	// 初始化索引配置
	// new clsIndex ( 已初始化的数据库类 或 数据库配置数组 );
	// new clsIndex ( $db );
	function clsIndex ( $db )
	{
		if ( is_array ( $db ) )
		{
			$this->dbConfig = $db;
		}
		elseif ( is_object ( $db ) )
		{
			$this->db = $db;
		}
		else
		{
			return false;
		}		
		$this->idxSettings = array ();
	}

	// 添加索引配置
	// addIdxSetting ( 表名前缀, 索引字段, 索引值字段, 转换值字段, ... );
	// addIdxSetting ( 'table_', 'key', 'name', 'value', ... );
	function addIdxSetting ( $tablePrefix, $keyField, $nameField, $valueField )
	{
		$args = func_get_args ();

		$tablePrefix = array_shift ( $args );
		$this->idxSettings[$tablePrefix] = $args;
	}

	// 初始化数据库
	function initDb ()
	{
		$this->db = init_db ( $this->dbConfig );
	}

	// 创建索引
	function create ( $tablePrefix )
	{
		$idxFields = $this->idxSettings[$tablePrefix];
		$args = func_get_args ();

		$tablePrefix = array_shift ( $args );

		$keyValue = $args[0];
		$indexKey = $this->keyEncode ( $keyValue );

		array_unshift ( $args, $indexKey );

		$arrInsert = array_combine ( $idxFields, $args );

		if ( !$this->db ) $this->initDb ();
		$this->db->insert ( $this->makeTableName ( $tablePrefix, $keyValue ), $arrInsert );
		if ( $this->db->affectedRows > 0 )
		{
			$this->db->commit ();
			return true;
		}
		else
		{
			return false;
		}
	}

	// 获取索引值
	function get ( $tablePrefix, $keyValue, $valueField )
	{
		$idxFields = $this->idxSettings[$tablePrefix];
		$indexKey = $this->keyEncode ( $keyValue );

		if ( !$this->db ) $this->initDb ();
		$ret = @current ( $this->db->select ( $this->makeTableName ( $tablePrefix, $keyValue ), "{$idxFields[0]} = '$indexKey'", '', 0, 0, $valueField ) );
		return $ret[$valueField];
	}

	// 删除索引
	function remove ( $tablePrefix, $keyValue )
	{
		$idxFields = $this->idxSettings[$tablePrefix];
		$indexKey = $this->keyEncode ( $keyValue );

		if ( !$this->db ) $this->initDb ();
		$this->db->delete ( $this->makeTableName ( $tablePrefix, $keyValue ), "{$idxFields[0]} = '$indexKey'" );
		if ( $this->db->affectedRows > 0 )
		{
			$this->db->commit ();
			return true;
		}
		else
		{
			return false;
		}
	}

	// 索引键值编码
	function keyEncode ( $value )
	{
		$value = md5 ( strtolower ( $value ) );
		return $value;
	}

	// 生成表名
	function makeTableName ( $tablePrefix, $keyValue )
	{
		$tableName = $tablePrefix . $this->tableNameSplitor . substr ( $this->keyEncode ( $keyValue ), 0, 1 );
		return $tableName;
	}
}
?>